import moment from 'moment'

/**
 * [getOnlyKey 获取唯一值]
 * @param {[String]} [str] [用于生成唯一值的字符串]
 * @return {[String]} [唯一值]
 */
export function getOnlyKey(str = 'key') {
  return `${str}_${new Date().getTime()}_${parseInt(
    Math.random() * Math.random() * 1000000
  )}`
}

/**
 * [toastMsg 提示弹窗]
 */
export function toastMsg(obj, { message, type }) {
  obj.$message({
    message,
    type
  })
}

/**
 * [confirmMsg 确认弹窗]
 */
export function confirmMsg(
  obj,
  {
    msg,
    dangerouslyUseHTMLString = false,
    confirmBtnText = '确定',
    cancelBtnText = '取消',
    showConfirmButton = true,
    showCancelButton = true,
    successCb,
    cancelCb
  }
) {
  obj
    .$confirm(msg, {
      dangerouslyUseHTMLString,
      confirmButtonText: confirmBtnText,
      cancelButtonText: cancelBtnText,
      showConfirmButton,
      showCancelButton,
      type: 'warning',
      iconClass: 'iconfont icontixing',
      center: true
    })
    .then(() => {
      if (successCb) {
        successCb()
      }
    })
    .catch(() => {
      if (cancelCb) {
        cancelCb()
      }
    })
}

/**
 * [cloneDeep 深拷贝]
 * @param  {[Object|Array]} data [需要深拷贝的数据]
 * @return {[Object|Array]}     [深拷贝出来的数据]
 */
export function cloneDeep(data) {
  let newData = null
  if (data instanceof Array) {
    // 数组
    newData = []
    for (const index in data) {
      newData.push(cloneDeep(data[index]))
    }
  } else if (typeof data === 'function') {
    // 函数
    newData = data
  } else if (data instanceof Object) {
    newData = {}
    for (const key in data) {
      newData[key] = cloneDeep(data[key])
    }
  } else {
    newData = data
  }
  return newData
}


/**
 * 时间格式化
 * @param {Date} date 日期时间
 * @param {String} format 格式
 */
export const dateFormat = (date, format) => {
  if (!date) {
    return ''
  }
  return moment(date).format(format)
}


/**
 * 判断是否为空，空的定义为undefined,null,'',[],{}
 */
export function isRealEmpty(value) {
  if (value === null || value === undefined) {
    return true
  } else if (typeof value === 'string') {
    return value === ''
  } else if (value instanceof Array) {
    return value.length === 0
  } else if (value instanceof Object) {
    return Object.keys(value).length === 0
  }
}


/**
 * [clearLocalStorage  清除指定参数的localStorage]
 */
export function clearLocalStorage() {
  if (sessionStorage.getItem(getStorageKey('authCode'))) {
    sessionStorage.removeItem(getStorageKey('authCode'))
  }
  if (localStorage.getItem('webTokenData')) {
    localStorage.removeItem('webTokenData')
  }
  if (localStorage.getItem(getStorageKey('webUserData'))) {
    localStorage.removeItem(getStorageKey('webUserData'))
  }
  if (localStorage.getItem('leftnav')) {
    localStorage.removeItem('leftnav')
  }
  if (localStorage.getItem('flowInfoData')) {
    localStorage.removeItem('flowInfoData')
  }
  if (sessionStorage.getItem('is_runtime_login')) {
    sessionStorage.removeItem('is_runtime_login')
  }
}

/**
 * [getImageAuthUrl 获取有权限的文件url]
 * @param  {[String]} fileId   [文件id]
 * @param  {[String]} filename [文件名]
 * @param  {[String]} extras.isAddToken [是否加token]
 * @return {[String]}          [有权限的文件url]
 */
export function getImageAuthUrl(
  fileId,
  filename,
  formInfoData = {},
  extras = {}
) {
  // 请求获取token的接口
  // 引入公共js
  const until = require('@/utils/until')
  let authUrl = ''
  const token = localStorage.getItem('webTokenData')
  const apiPath = until.apiPath + 'bpms-runtime/'
  const fdnStoragePath = until.apiPath + 'fdn-storage/'
  // 获得授权回显的图片url
  const { formDefinitionId, fieldId, applicationId } = formInfoData
  authUrl = `${apiPath}forms/${formDefinitionId}/form_fields/file_upload/${fieldId}/download?applicationId=${applicationId}&fileName=${encodeURIComponent(filename)}&id=${fileId}`
  // 针对外部表单的处理
  const inExForm = window.location.hash.indexOf('/externalForm') > -1 || window.location.hash.indexOf('/queryExternalForm') > -1
  if (inExForm) {
    authUrl = authUrl.replace('/bpms-runtime/form', '/bpms-externalform/mutual/form')
  } else {
    authUrl = `${fdnStoragePath}oss/files/${fileId}/data?`
  }
  if (extras.isAddToken && !inExForm) {
    if (extras.isAddToken) {
      // 是否添加Token
      authUrl += `&X-Auth0-Token=${token}`
    }
    if (extras.thumbnail) {
      // 是否添加缩略图参数
      authUrl += `&thumbnail=true`
    }
  }
  return authUrl
}



// 判断是否为对象
export const isObject = obj => {
  return Object.prototype.toString.call(obj) === '[object Object]'
}

// 判断是否为对象
export const isArray = obj => {
  return Object.prototype.toString.call(obj) === '[object Array]'
}

export function debounce(fn, interval) {
  let timer = null
  return () => {
    clearTimeout(timer)
    timer = setTimeout(fn, interval)
  }
}

/**
 * [setTitleForLabel 为label设置title]
 * @param {[Object]} el 根元素
 */
export function setTitleForLabel(el) {
  if (el && el.querySelectorAll) {
    const labelArr = el.querySelectorAll('label.el-form-item__label')
    if (labelArr) {
      labelArr.forEach(res => {
        let text = res.innerText
        // 过滤最后的'：' -- by 老郑 20190605
        if (text && text.substr(text.length - 1) === '：') {
          text = text.substr(0, text.length - 1)
        }
        res.title = text
        if (res.className && res.className.indexOf('labelWithColon') === -1) {
          res.className += ' labelWithColon'
        }
      })
    }
  }
}



let openDataBindTimer = null
/**
 * 开放域渲染（用户名称/部门名称）
 * !!!注意，需要使用v-html进行渲染!!!
 * （判断传入的值中是否需要使用企业微信的open-data组件进行渲染）
 * @param {String} val 字段返回的value值
*/
export function checkOpenData(val) {
  if (/\$userName=|\$departmentName=/.test(val)) {
    const dataList = val.match(/(\$userName=|\$departmentName=)(.*?)\$/g)
    dataList && dataList.forEach(item => {
      const type = item.split('=')[0].substr(1)
      const openid = item.split('=')[1].substr(0, item.split('=')[1].length - 1)
      val = val.replace(item, `<ww-open-data type="${type}" openid="${openid}"></ww-open-data>`)
    })
    // /**
    //  * 由于腾讯侧无法100%检测到opendata标签的变动，
    //  * 会导致在window里微信/企业微信的页面出现部分正常渲染，部分无法正常渲染的情况，
    //  * 为了修复这个BUG，只能在渲染了opendata标签的逻辑里动刀子，
    //  * 通过定时来延迟执行bind逻辑
    //  */
    clearTimeout(openDataBindTimer)
    openDataBindTimer = setTimeout(function() {
      if (window.WWOpenData && window.WWOpenData.bindAll) {
        window.WWOpenData.bindAll(document.querySelectorAll('ww-open-data'))
        // 为了处理评论中的富文本问题
        if (window.frames && window.frames.length > 0) {
          const framesNum = window.frames.length
          for (let i = 0; i < framesNum; i++) {
            if (window.frames[i] && window.frames[i].document) {
              window.WWOpenData.bindAll(window.frames[i].document.querySelectorAll('ww-open-data'))
            }
          }
        }
      }
    }, 100)
    return val
  }
  return val
}

// 获取用户信息
export async function getUsersDetail(ids = []) {
  try {
    const res = (await structApi.getOrganizationDetailedInfo({ users: ids }))
      .data
    if (res.code === 0) {
      if (res.data && res.data.users) {
        const resObj = {}
        // 把办理者id作为键，信息作为值
        res.data.users.map(item => {
          resObj[item.id] = item
        })
        return resObj
      }
    } else {
      this.$message.error(res.msg)
    }
  } catch (error) {
    this.$message.error(error)
  }
  return {}
}


// 根据时间戳转日期格式
export function timetrans(time, str) {
  const date = new Date(time)
  const Y = date.getFullYear() + '-'
  const M =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-'
  const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
  const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  const m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  switch (str) {
    case 'y':
      return Y + M + D + '  ' + h + m
    case 'm':
      return M + D + '  ' + h + m
  }
}
/**
 * [getBrowserEnv 判断当前浏览器的环境]
 * @return {[Object]}
 */
export function getBrowserEnv() {
  const ua = navigator.userAgent.toLowerCase()
  const isWxWork = /wxwork/i.test(ua) && /micromessenger/i.test(ua)
  const isWx = !isWxWork && /micromessenger/i.test(ua)
  const isPC = !/android|webos|iphone|ipod|blackberry/i.test(ua)
  const isMobile = /mobile/i.test(ua)
  const isIOS = !!ua.match(/\(i[^;]+;( u;)? cpu.+mac os x/)
  const isAndroid = ua.indexOf('android') > -1 || ua.indexOf('adr') > -1
  const isAndroidWxWork = isWxWork && isAndroid
  const isIOSWxWork = isWxWork && isIOS
  const isMac = /macintosh/i.test(ua)
  const isWindow = /windows/i.test(ua)
  return {
    isWx,
    isWxWork,
    isPC,
    isMobile,
    isIOS,
    isAndroid,
    isAndroidWxWork,
    isIOSWxWork,
    isMac,
    isWindow
  }
}

/**
 * getStorageKey 用于更新生产域名不同上下文本地缓存的信息
 * 先改造userData qiqiao2-webUserData
 */
export function getStorageKey(key) {
  const until = require('@/utils/until')
  // 当前系统版本key，私有化没有上下文时提供一个默认前缀
  const context = until.context || 'qiqiao/private'
  return `${context}-${key}`
}

/**
 * escapeText 特殊字符反转义
 * @param  {String} text 传入需要转换的字符串
 * @return {String} val 字段返回的value值
 */
export function escapeText(text) {
  if (typeof (text) !== 'string') {
    return text
  }
  // 抽离成可配置的匹配列表
  const matchList = {
    '&lt;': '<',
    '&gt;': '>',
    '&amp;': '&',
    '&#34;': '"',
    '&quot;': '"',
    '&#39;': `'`
  }
  // ------------【*提取匹配列表key值*】.【组数转字符串】
  let regStr = '(' + Object.keys(matchList).toString() + ')'
  // 通过匹配将其更新为正则的字符串类型
  regStr = regStr.replace(/,/g, ')|(')
  // ------- 字符串 转 正则 方法
  const regExp = new RegExp(regStr, 'g')
  // ------ 替换方法 (正则, 当前key => 返回当前被匹配的key值)
  return text.replace(regExp, match => matchList[match])
}



export function getProjectContext() {
  return process.env.NODE_ENV === 'production' ? until.context : ''
}

/**
 * 页面跳转
 * @param {Object} data
 */
export function routerPush(data) {
  if (data.mode === 'spa' && data.vm) {
    const routerParams = {
      name: data.name,
      params: data.params,
      query: data.query,
      path: data.path
    }
    data.vm.$router.push(routerParams)
  } else if (data.mode === 'mpa') {
    const dir = getProjectContext()
    let targetUrl =
      window.location.origin +
      dir +
      (data.pageName ? `/${data.pageName}` : '') +
      (window.location.search ? `/${window.location.search}` : '/')
    if (data.path) {
      targetUrl += '#/' + data.path
    }
    if (data.query) {
      targetUrl += serialize(data.query)
    }
    if (data.hasOwnProperty('isDeveloperCenter') && !data.isDeveloperCenter && data.pageName === 'developerCenter') {
      window.open(targetUrl, '_blank')
    } else {
      window.location.href = targetUrl
    }
  }
}